package com.beijing.cyou.redis;


import java.util.Set;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.beijing.cyou.config.RedisConnection;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Repository
public class RedisRepository implements InitializingBean {

	@Autowired
	private RedisConnection redisConnection ;
	
	private final static Integer poolDefault = 0 ;
	
	private JedisPool jedisPool ;

	private boolean flag ;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		jedisPool = redisConnection.chooseJedisPool(poolDefault) ;		
	}
	
	public boolean resetRedisPool(Integer dbnum) {
		flag = false ;
		jedisPool = redisConnection.chooseJedisPool(dbnum);
		flag = jedisPool!= null ? true : false ;
		return flag ;
	}
	
	private String value ;

	public Set<String> listVagueKeys(String vaguePattern){
		Jedis jedis = null ;
		Set<String> result = null ;
		try {
			jedis = jedisPool.getResource();
			result = jedis.keys(vaguePattern);
			return result ;
		}finally {
			jedis.close();
		}
	}

	public boolean redisKeyExist(String key){
	    flag = false ;
        Jedis jedis = null ;
        try {
            jedis = jedisPool.getResource();
            flag = jedis.exists(key);
            return flag ;
        } finally {
            jedis.close();
        }
    }

    public boolean existInSet(String key, String member) {
        flag = false ;
        Jedis jedis = null ;
        try {
            jedis = jedisPool.getResource() ;
            flag = jedis.sismember(key, member);
            return flag ;
        }finally {
            jedis.close();
        }
    }

    public void setString(String key, String value) throws Exception {
        Jedis jedis = null;  
        try {  
            jedis = jedisPool.getResource();  
            jedis.set(key, value);  
        } finally {  
            jedis.close();  
        }  
    }  
      
    public String getString(String key) throws Exception  {  
        Jedis jedis = null;  
        try {  
            jedis = jedisPool.getResource();  
            value = jedis.get(key);
            return value;  
        } finally {  
            jedis.close();  
        }  
    } 
    
    public void insertToSet(String key, String member) {
    	Jedis jedis = null ;
    	try {
    		jedis = jedisPool.getResource() ;
    		jedis.sadd(key, member);
    	}finally {
			jedis.close();
		}
    	
    }

    public Set<String> listSet(String key){
    	Set<String> set = null ;
    	Jedis jedis = null ;
    	try {
    		jedis = jedisPool.getResource() ;
    		set = jedis.smembers(key);
    		return set ;
    	}finally {
    		jedis.close();
		}
    }
	
}
